'''gaoyunzhi@gmail.com
12:56 PM 10/15/2012
get the local fname of a webpage
currently saveing as the same as the last piece of the address, without extension
input: webpage link
output: local fname
'''

def toFname(link,hasHtml=True):
    ind=link.find('wikipedia.org')
    if ind!=-1:
        link=link[:ind]+link[ind+len('en.wikipedia.org'):]
    ind=link.find('api.php?action=query&prop=revisions&rvlimit=1&format=xml')
    if ind!=-1:
        link=link[:ind]+link[ind+len('api.php?action=query&prop=revisions&rvlimit=1&format=xml')                             :]
    while link[-1]=='/': link=link[:-1]
    ind=link.rfind('/')
    if ind==-1:
        print link+' is not a valid web address'
        return None
    pre=link[:ind]
    link=link[ind+1:]
    ind=link.find('.')
    if ind!=-1 and ind+10>len(link):
        link=link[:ind]
    link=link+'('+pre+')'
    ans=[]
    #link=link.translate(None,'\ / : * ? " < > |')
    for i in range(len(link)):
        if link[i] not in ['\ '[:-1],'/ '[:-1],': '[:-1],'* '[:-1],\
                           '? '[:-1],'" '[:-1],'< '[:-1],'> '[:-1],'| '[:-1] ]:
            ans.append(link[i])
        if link[i]  in ['\ '[:-1],'/ '[:-1]]:
            ans.append('-')
    if hasHtml==True:
        return ''.join(ans)+'.html'
    else:
        return ''.join(ans)

def test():
    print toFname('http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvlimit=1&format=xml&titles=59th_Street_%E2%80%93_Columbus_Circle_(IRT_Broadway_%E2%80%93_Seventh_Avenue_Line)&rvstart=20100101')
    #print toFname('http://en.wikibooks.org/wiki/Python_Programming/Strings')
    #print toFname('Strings')
    #print toFname('http://en.wikibooks.org/wiki/Python_Programming/Strings')

if __name__=='__main__':
    print 'this is a file contains Tofname, which get the local fname of a webpage'
    print 'running test'
    test()
